package com.itheima.aspect;


import com.itheima.domain.po.Emp;
import com.itheima.domain.po.EmpLoginLog;
import com.itheima.domain.po.LoginResult;
import com.itheima.domain.vo.Result;
import com.itheima.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
public class LoginAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("execution(* com.itheima.controller.LoginController.login(..))")
    public Object loginLog(ProceedingJoinPoint pjp) throws Throwable {
        Long start = System.currentTimeMillis();
        //获取用户名和密码
        Emp emp = (Emp) pjp.getArgs()[0];
        log.info("用户{}正在登录",emp.getName());
        String username = emp.getUsername();
        String password = emp.getPassword();
        //登录时间
        LocalDateTime loginTime = LocalDateTime.now();
        //执行原始方法，获取结果
        Result result = (Result) pjp.proceed();
        Integer isSuccess = result.getCode();//获取登录code，登录成功为1，登录失败为0
        String jwt = null;
        if (isSuccess == 1) {
            log.info("用户{}登录成功",username);
            LoginResult loginResult = (LoginResult) result.getData();
            jwt = loginResult.getToken();
        }
        Long end = System.currentTimeMillis();
        Long costTime = end - start;
        //封装数据
        EmpLoginLog empLoginLog = new EmpLoginLog(null,username,password,loginTime,isSuccess,jwt,costTime);
        //调用方法，插入日志
        operateLogMapper.insertLoginLog(empLoginLog);

        return result;
    }
}
